package com.hctrl.mybatis.metaObject;


import com.hctrl.mybatis.metaObject.annotation.FieldMapped;
import com.hctrl.mybatis.metaObject.decorator.MetaObjectDecorator;
import com.hctrl.mybatis.metaObject.entity.UserDO;
import com.hctrl.mybatis.metaObject.factory.MetaObjectFactory;
import org.apache.ibatis.reflection.MetaObject;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author hanchao
 * @version 1.0
 * @date 2022/5/24 22:01
 */
public class Client {

    public static void main(String[] args) {

        /**
         * 构建前端传递的数据
         */
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("name_pre","hanchao");
        paramMap.put("phone_pre","18888888888");
        paramMap.put("age_pre","18");
        paramMap.put("birthday_pre","1998-03-11");

        Map<String,String> fieldMapped = processFieldMapped(UserDO.class);
        UserDO userDO = new UserDO();
        MetaObject metaObject = MetaObjectFactory.getObjectInstance(userDO);
        MetaObjectDecorator decorator = new MetaObjectDecorator();
        decorator.setMetaObject(metaObject);

        Set<Map.Entry<String, String>> entries = paramMap.entrySet();
        for (Map.Entry<String, String> entry : entries){
            String key = entry.getKey();
            String fieldName = fieldMapped.get(key);
            decorator.setValue(fieldName,entry.getValue());
        }
        System.out.println(metaObject.getOriginalObject());
    }

    private static Map<String, String> processFieldMapped(Class<UserDO> userDOClass) {

        Map<String,String> map = new HashMap<>();
        Field[] declaredFields = userDOClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            field.setAccessible(true);
            FieldMapped annotation = field.getAnnotation(FieldMapped.class);
            map.put(annotation.value(),field.getName());
        }
        return map;
    }

}
